package com.wuqing;

import com.wuqing.bean.MethodInvokeRecord;
import com.wuqing.utils.TpMonitorHelper;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.*;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author wuqing
 * @date 2020/8/4
 */
@Activate(group = {/*CommonConstants.PROVIDER,*/ CommonConstants.CONSUMER})
public class DubboTpFilter implements Filter {

    private final ExecutorService executor = Executors.newSingleThreadExecutor(
            new NamedThreadFactory("DubboTpFilter-task"));

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long start = System.currentTimeMillis();
        String serviceName = invocation.getServiceName();
        String methodName = invocation.getMethodName();

        Result result = invoker.invoke(invocation);
        long cost = System.currentTimeMillis() - start;

        // String format = String.format("serviceName=%s,serviceName=%s,执行时间cost=%s", serviceName, methodName, cost);
        // System.out.println(format);

        //记录队列中添加 请求调用记录
        executor.submit(() -> TpMonitorHelper.addRecord(new MethodInvokeRecord(serviceName, methodName, cost, start)));

        return result;
    }

}